<?php
error_reporting("E_ALL");ini_set("display_errors", 1);
header("content-Type: application/json; charset=utf-8");
include("SMTPMailer.class.php");
function ajaxReturn($array){
    $content=json_encode($array);
    if(empty($_GET['callback'])){
        echo $content;exit;
    }else{
        echo $_GET['callback']."(".$content.")";exit;
    }
}
$post = $_POST;
if(empty($post)){
    $return=[];
    $return['code']=201;
    $return['msg']='请提交POST数据';
    ajaxReturn($return);
}
if(empty($post['username'])){
    $return=[];
    $return['code']=201;
    $return['msg']='请提交用户名';
    ajaxReturn($return);
}
if(empty($post['password'])){
    $return=[];
    $return['code']=201;
    $return['msg']='请提交密码';
    ajaxReturn($return);
}
if(empty($post['to'])){
    $return=[];
    $return['code']=201;
    $return['msg']='请提交收件人';
    ajaxReturn($return);
}
if(empty($post['subject'])){
    $return=[];
    $return['code']=201;
    $return['msg']='请提交邮件标题';
    ajaxReturn($return);
}
if(empty($post['message'])){
    $return=[];
    $return['code']=201;
    $return['msg']='请提交邮件内容';
    ajaxReturn($return);
}
if(empty($post['host']))$post['host']='smtp.qq.com';
if(empty($post['port']))$post['port']=465;
if(empty($post['from']))$post['from']=$post['username'];

try {
    // QQ邮箱配置示例
    $mailer = new SMTPMailer($post['host'], $post['port'], $post['username'], $post['password'],SMTPMailer::ENCRYPT_SSL);
    if(!empty($post['is_html']))$mailer->is_html = true;
   //$mailer->setDebug(true);
    
    $res = $mailer->send($post['from'],  // 发件人
        explode(',',$post['to']), // 收件人数组
        $post['subject'], 
        $post['message']
       // ,array(), // 自定义头
        //array('/path/to/file.zip') // 附件路径
    );
    $return=[];
    $return['code']=200;
    $return['msg']="邮件发送成功";
    //$return['data']=$res;
    ajaxReturn($return);
} catch (Exception $e) {
    $return=[];
    $return['code']=201;
    $return['msg']="发送失败: ".$e->getMessage();
    ajaxReturn($return);
}
?>